<template>
  <view class="audio-player">
    <view class="title">音频播放示例（支持 iOS 静音播放）</view>
    <u-button @click="show = true" text="打开ActionSheet"></u-button>
    <view class="controls">
      <button class="btn" @tap="togglePlay">{{ playing ? '暂停' : '播放' }}</button>
      <button class="btn" @tap="stop">停止</button>
    </view>

    <view class="progress" @tap="seekByTap">
      <view class="bar">
        <view class="played" :style="{ width: progressPercent + '%' }"></view>
      </view>
      <view class="time">
        <text class="t">{{ formatTime(currentTime) }}</text>
        <text class="t">{{ formatTime(duration) }}</text>
      </view>
    </view>

    <view class="status">
      <text>状态：{{ statusText }}</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      src: 'http://47.119.138.95:9133/test.mp3',
      audio: null,
      playing: false,
      duration: 0,
      currentTime: 0,
      progressPercent: 0,
      canPlay: false,
      statusText: '未播放'
    }
  },
  onLoad() {
    // 仅在微信小程序环境设置 iOS 静音播放选项
    // #ifdef MP-WEIXIN
    if (typeof uni.setInnerAudioOption === 'function') {
      try {
        uni.setInnerAudioOption({
          obeyMuteSwitch: false,  // iOS 静音开关下仍可播放
          mixWithOther: true      // 与其他音频混音，避免被打断
        });
      } catch (e) {
        // 忽略不支持的情况
      }
    }
    // #endif

    // 创建音频实例
    const audio = uni.createInnerAudioContext();
    audio.src = this.src;
    audio.autoplay = false;
    audio.loop = false;

    // 确保 iOS 静音也播放
    // #ifdef MP-WEIXIN
    audio.obeyMuteSwitch = false;
    audio.mixWithOther = true;
    // #endif

    // 事件绑定
    audio.onCanplay(() => {
      this.canPlay = true;
      this.statusText = '可播放';
      // 某些机型 duration 需在 canplay 后延迟获取
      setTimeout(() => {
        if (audio.duration && !isNaN(audio.duration)) {
          this.duration = Math.floor(audio.duration);
        }
      }, 100);
    });

    // audio.onDurationChange(() => {
    //   if (audio.duration && !isNaN(audio.duration)) {
    //     this.duration = Math.floor(audio.duration);
    //   }
    // });

    audio.onPlay(() => {
      this.playing = true;
      this.statusText = '播放中';
    });

    audio.onPause(() => {
      this.playing = false;
      this.statusText = '已暂停';
    });

    audio.onEnded(() => {
      this.playing = false;
      this.currentTime = 0;
      this.progressPercent = 0;
      this.statusText = '播放结束';
    });

    audio.onTimeUpdate(() => {
      this.currentTime = audio.currentTime || 0;
      if (audio.duration && !isNaN(audio.duration) && audio.duration > 0) {
        this.duration = Math.floor(audio.duration);
        this.progressPercent = Math.min(100, (this.currentTime / audio.duration) * 100);
      }
    });

    audio.onError((err) => {
      console.error('audio error:', err);
      this.statusText = '播放错误';
      uni.showToast({ title: '音频播放错误', icon: 'none' });
    });

    this.audio = audio;
  },
  onUnload() {
    if (this.audio) {
      try {
        this.audio.stop();
        this.audio.destroy();
      } catch (e) {}
      this.audio = null;
    }
  },
  methods: {
    togglePlay() {
	  console.log('this.audio', this.audio)
      if (!this.audio) return;
      if (this.playing) {
        this.audio.pause();
      } else {
        // 部分 iOS/机型需用户手势触发播放，此按钮点击即为手势
        // 如果还未可播放，尝试先调用 play，WeChat 会在资源就绪后开始
        this.audio.play();
      }
    },
    stop() {
      if (!this.audio) return;
      this.audio.stop();
      this.playing = false;
      this.currentTime = 0;
      this.progressPercent = 0;
    },
    seekByTap(e) {
      if (!this.audio || !this.duration || this.duration <= 0) return;
      // 计算点击位置占比
      const touchX = e.detail.x; // 小程序中为点击相对屏幕的坐标，需换算
      // 通过节点信息获取进度条宽度与左偏移
      const query = uni.createSelectorQuery().in(this);
      query.select('.bar').boundingClientRect(rect => {
        if (!rect) return;
        const relativeX = e.detail.x - rect.left;
        const ratio = Math.max(0, Math.min(1, relativeX / rect.width));
        const target = Math.floor(this.duration * ratio);
        try {
          this.audio.seek(target);
          // 立即更新 UI
          this.currentTime = target;
          this.progressPercent = Math.min(100, (target / this.duration) * 100);
        } catch (err) {
          console.warn('seek failed:', err);
        }
      }).exec();
    },
    formatTime(sec) {
      if (!sec || isNaN(sec)) return '00:00';
      const s = Math.floor(sec);
      const m = Math.floor(s / 60);
      const r = s % 60;
      const mm = m < 10 ? '0' + m : '' + m;
      const rr = r < 10 ? '0' + r : '' + r;
      return mm + ':' + rr;
    }
  }
}
</script>

<style scoped>
.audio-player {
  padding: 16rpx;
}

.title {
  font-size: 32rpx;
  font-weight: 600;
  margin-bottom: 24rpx;
}

.controls {
  display: flex;
  gap: 16rpx;
  margin-bottom: 24rpx;
}

.btn {
  padding: 12rpx 24rpx;
  background-color: #07c160; /* 微信绿 */
  color: #fff;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.progress {
  margin-top: 12rpx;
}

.bar {
  position: relative;
  height: 8rpx;
  background-color: #e5e5e5;
  border-radius: 8rpx;
  overflow: hidden;
}

.played {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  background-color: #07c160;
  width: 0%;
  transition: width 0.1s linear;
}

.time {
  display: flex;
  justify-content: space-between;
  margin-top: 12rpx;
}

.time .t {
  font-size: 24rpx;
  color: #666;
}

.status {
  margin-top: 16rpx;
  font-size: 26rpx;
  color: #333;
}
</style>